/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package jndidatabaseyejb;

import ejbs.FicheroRemote;
import es.exes.ServicioFichero;
import es.exes.FicheroServicioWeb;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author odeen
 */
public class Main {

    @Resource(mappedName = "jms/Queue")
    private static Queue queue;
    @Resource(mappedName = "jms/QueueFactory")
    private static ConnectionFactory queueFactory;
    @Resource(name = "mail/Session")
    private static Session mailSession;
    @EJB
    private static FicheroRemote ficheroBean;
    @Resource(mappedName = "jdbc/pool", type = DataSource.class)
    private static DataSource ds;
    /*    @WebServiceRef(wsdlLocation="http://localhost:8080/JNDI-DataBaseYEjb-ejb/Servicio?WSDL")
    private static FicheroServicioWeb servicio;
*/

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws NamingException {
        // TODO code application logic here
        try {
            if (ficheroBean == null) {
                System.out.println("Buscando en el contexto de nombrado");
                Properties props = new Properties();
                props.setProperty("java.naming.factory.initial",
                        "com.sun.enterprise.naming.SerialInitContextFactory");


                props.setProperty("java.naming.factory.url.pkgs",
                        "com.sun.enterprise.naming");


                props.setProperty("java.naming.factory.state",
                        "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
                props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");                
                props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");

                Context ctx = new InitialContext(props);



                ficheroBean = (FicheroRemote) ctx.lookup(FicheroRemote.class.getName());
                System.out.println("EJB hallado");

                ds = (DataSource) ctx.lookup("jdbc/pool");
                System.out.println("DataSource hallado");

                queueFactory = (ConnectionFactory) ctx.lookup("jms/QueueFactory");
                System.out.println("JMS factory hallada");
                queue = (Queue) ctx.lookup("jms/Queue");
                System.out.println("JMS queue hallada");

                mailSession = (Session) ctx.lookup("mail/Session");
                System.out.println("Mail session hallada");
            }
        } catch (Exception ex) {
            System.out.println("ERROR: " + ex.getMessage());
        } finally {
            try {
                ServicioFichero ficheroServicio = new ServicioFichero();
                FicheroServicioWeb fichero = ficheroServicio.getPuertoFichero();
                System.out.print("Usando Servicio Web: ");
                System.out.println("¿Existe /home? " + fichero.existe("/home"));
            } catch (Exception ex) {
                System.out.println("MAL: " + ex.getMessage());
            }
            try {
                System.out.print("Usando EJB: ");
                System.out.println("¿Existe /home? " + ficheroBean.existe("/home"));
            } catch (Exception ex) {
                System.out.println("MAL: " + ex.getMessage());
            }
            try {
                System.out.print("Usando Datasource: ");
                ds.getConnection().close();
                System.out.println("OK DataSource");
            } catch (SQLException ex) {
                System.out.println("MAL: " + ex.getMessage());
            }
            try {
                System.out.print("Enviando JMS: ");
                sendJMSMessageToQueue("Este es el mensaje");
                System.out.println("OK envio JMS");
            } catch (JMSException ex) {
                System.out.println("MAL: " + ex.getMessage());
            }
            try {
                System.out.print("Enviando correo: ");
                sendMail("vgarcia@exescampus.com", "Asunto: pruebas", "El contenido del mensaje");
                System.out.println("OK envio mail");
            } catch (MessagingException ex) {
                System.out.println("MAL: " + ex.getMessage());
            }





        }

    }

    private static void sendMail(String email, String subject, String body) throws NamingException, MessagingException {
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setRecipients(RecipientType.TO, InternetAddress.parse(email, false));
        message.setText(body);
        mailSession.getTransport().send(message);
//        Transport.send(message);


    }

    private static Message createJMSMessageForjmsQueue(javax.jms.Session session, Serializable messageData) throws JMSException {
        // TODO create and populate message to send
        ObjectMessage tm = session.createObjectMessage();
        tm.setObject(messageData);
        return tm;
    }

    private static void sendJMSMessageToQueue(Serializable messageData) throws JMSException {
        Connection connection = null;
        javax.jms.Session session = null;
        try {
            connection = queueFactory.createConnection();
            session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(queue);
            messageProducer.send(createJMSMessageForjmsQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(Main.class.getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
